﻿using System;
using System.IO;
using BattlelogMobile.Core.Message;
using GalaSoft.MvvmLight.Messaging;

namespace BattlelogMobile.Core.Service
{
    public class UserIdResolver : IUserIdResolver
    {
        private const string UnableToParseUserId = "Unable to retrieve user id";
        private const string UserIdBlockStart = "/dogtags/";

        public void Resolve(Stream stream)
        {
            try
            {
                using (var reader = new StreamReader(stream))
                {
                    string buffer = reader.ReadToEnd();
                    reader.Close();

                    int startPosition = buffer.IndexOf(UserIdBlockStart, StringComparison.Ordinal);
                    buffer = buffer.Substring(startPosition + UserIdBlockStart.Length);
                    long userId = Convert.ToInt64(buffer.Substring(0, buffer.IndexOf("/", StringComparison.Ordinal)));
                    Messenger.Default.Send(new UserIdResolvedMessage(userId));
                }
            }
            catch (Exception e)
            {
                if (e is ArgumentNullException || e is FormatException)
                    Messenger.Default.Send(new BattlelogResponseMessage(UnableToParseUserId, false));
                else
                    throw;
            }
        }
    }
}
